package thread.threaddemo;

import java.sql.Time;
import java.util.concurrent.TimeUnit;

/**
 * @Author: wenjingyuan
 * @Date: 2023/02/11/21:17
 * @Description:waitVSsleep
 */
public class WaitSleepDemo2 {
    public static void main(String[] args) {
        Object lock=new Object();
        Object lock2=new Object();
        Thread t1=new Thread(()->{
            synchronized (lock){
                System.out.println("线程1：开始执行");
                try {
                    lock.wait(3*1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("线程1：结束执行");
            }
        },"wait0");
        t1.start();
        Thread t2=new Thread(()->{
            synchronized (lock2){
            System.out.println("线程2：开始执行");
            try {
                Thread.sleep(3*1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("线程2：结束执行");}
        },"sleep0");
        t2.start();
        //接下来我们使用两个线程来尝试获取锁，首先先将两个线程休眠一秒钟
        //目的是为了让线程12都可以真正进入到休眠中
        //接下来尝试获取锁，如果能获取到锁说明该锁被释放了
        // 如果获取不到锁那么说明该锁没有被释放
        Thread t3=new Thread(()->{
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //其次我们可以尝试获取锁
            System.out.println("尝试获取wait方法的锁");
            synchronized (lock){
                System.out.println("成功获取到wait方法的锁");
            }
        },"wait1");
        t3.start();
        Thread t4=new Thread(()->{
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //其次我们可以尝试获取锁
            System.out.println("尝试获取sleep方法的锁");
            synchronized (lock2){
                System.out.println("成功获取到sleep方法的锁");
            }
        },"sleep1");
        t4.start();
    }
}
